import { useModel } from "umi";
import { useReactive } from "ahooks";
import compress from "gql-compress";

const userPublishPersonVersion = () => {
    const { remoteData, graphqlFetchPlatform } = useModel("global");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
    });

    const publishVersion = async (operatorCenter, version, callback) => {
        state.loading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceUrl: operatorCenter.url,
            serviceName: "/resource/referenceDatabase/person/saveVersion",
            params: { version },
        });
        if (res) {
            let res = await graphqlFetchPlatform({
                query,
                variables: {
                    uuid: version.uuid,
                    publishRecord: {
                        ...version.publishRecord,
                        [operatorCenter.runEnv]: {
                            time: new Date().getUTCTime(),
                            uuid: baseInfo.uuid,
                            name: baseInfo.realName,
                        },
                    },
                },
            });
            res && callback && callback(res);
        }
        state.loading = false;
    };

    return { ...state, publishVersion };
};

const query = compress(`mutation MyMutation(
    $uuid: UUID!,
    $publishRecord: JSON!
) {
    updatePersonReferenceDatabaseVersionByUuid(
        input: {
            uuid: $uuid
            personReferenceDatabaseVersionPatch: {
                publishRecord: $publishRecord
            }
        }
    ) {
        clientMutationId
    }
}`);

export default userPublishPersonVersion;
